package com.zhugang.week02;

/**
 * @program algorithms
 * @description: middleNode
 * @author: chanzhugang
 * @create: 2022/05/29 16:08
 */
public class MiddleNode2 {

    /**
     * 876. 链表的中间结点
     *
     * @param head
     * @return
     */
    public ListNode middleNode(ListNode head) {
        // 快慢指针：慢指针每次走一步，快指针每次走两步
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}